import java.util.ArrayList;
import java.util.List;

/**
 * 剑指 Offer 34. 二叉树中和为某一值的路径
 * https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
 */
public class Solutions_Offer_34 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.left = new TreeNode(5);
        root.right.right.right = new TreeNode(1);
        int sum = 22;  // output: {{5, 4, 11, 2}, {5, 8, 4, 5}}

        List<List<Integer>> result = pathSum(root, sum);
        System.out.println(result);
    }

    public static List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        pathSum(root, sum, res, list);
        return res;
    }

    public static void pathSum(TreeNode root, int sum, List<List<Integer>> res,
                               List<Integer> list) {
        if (root == null) {
            return;
        }
        // 添加元素
        list.add(root.val);
        if (sum == root.val && root.left == null && root.right == null) {
            // 为叶子节点且最后节点值等于 sum 时，添加结果
            res.add(new ArrayList<>(list));
        }
        pathSum(root.left, sum - root.val, res, list);
        pathSum(root.right, sum - root.val, res, list);
        // 移除元素
        list.remove(list.size() - 1);
    }
}
